package com.gcloud.controller.compute.service.vm.base.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gcloud.common.util.StringUtils;
import com.gcloud.controller.compute.dao.InstanceDao;
import com.gcloud.controller.compute.dao.InstanceTypeDao;
import com.gcloud.controller.compute.dao.ZoneDao;
import com.gcloud.controller.compute.dao.ZoneInstanceTypeDao;
import com.gcloud.controller.compute.dispatcher.Dispatcher;
import com.gcloud.controller.compute.entity.AvailableZoneEntity;
import com.gcloud.controller.compute.entity.InstanceType;
import com.gcloud.controller.compute.entity.VmInstance;
import com.gcloud.controller.compute.entity.ZoneInstanceTypeEntity;
import com.gcloud.controller.compute.handler.api.model.DescribeInstanceTypesParams;
import com.gcloud.controller.compute.handler.api.model.DescribeInstancesParams;
import com.gcloud.controller.compute.model.vm.AssociateInstanceTypeParams;
import com.gcloud.controller.compute.model.vm.CreateInstanceTypeParams;
import com.gcloud.controller.compute.model.vm.DeleteInstanceTypeParams;
import com.gcloud.controller.compute.model.vm.DetailInstanceParams;
import com.gcloud.controller.compute.model.vm.DetailInstanceTypeParams;
import com.gcloud.controller.compute.model.vm.ModifyInstanceTypeParams;
import com.gcloud.controller.compute.service.vm.base.IVmBaseService;
import com.gcloud.controller.compute.utils.NoVncUtil;
import com.gcloud.controller.image.dao.ImageDao;
import com.gcloud.controller.image.entity.Image;
import com.gcloud.controller.network.dao.FloatingIpDao;
import com.gcloud.controller.network.dao.IpallocationDao;
import com.gcloud.controller.network.dao.PortDao;
import com.gcloud.controller.network.entity.FloatingIp;
import com.gcloud.core.cache.container.CacheContainer;
import com.gcloud.core.cache.enums.CacheType;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.core.messagebus.MessageBus;
import com.gcloud.core.util.MessageUtil;
import com.gcloud.framework.db.PageResult;
import com.gcloud.header.api.model.CurrentUser;
import com.gcloud.header.compute.enums.VmState;
import com.gcloud.header.compute.enums.VmStepState;
import com.gcloud.header.compute.msg.api.model.DetailInstance;
import com.gcloud.header.compute.msg.api.model.DetailInstanceType;
import com.gcloud.header.compute.msg.api.model.InstanceAttributesType;
import com.gcloud.header.compute.msg.api.model.InstanceTypeItemType;
import com.gcloud.header.compute.msg.api.model.TplInstanceItem;
import com.gcloud.header.compute.msg.api.model.TplInstanceResponse;
import com.gcloud.header.compute.msg.api.model.TplNetworkInterfaceItem;
import com.gcloud.header.compute.msg.api.model.TplNetworkInterfaceItems;
import com.gcloud.header.compute.msg.api.model.ZoneInfo;
import com.gcloud.header.compute.msg.api.vm.tpl.ApiTplInstancesMsg;
import com.gcloud.header.compute.msg.node.vm.base.ModifyPasswordMsg;
import com.gcloud.header.compute.msg.node.vm.base.QueryInstanceVNCMsg;
import com.gcloud.header.compute.msg.node.vm.base.QueryInstanceVNCMsgReply;
import com.gcloud.header.compute.msg.node.vm.base.RebootInstanceMsg;
import com.gcloud.header.compute.msg.node.vm.base.StartInstanceMsg;
import com.gcloud.header.compute.msg.node.vm.base.StopInstanceMsg;
import com.gcloud.header.network.model.InstanceNetworkInterfaceItem;
import com.gcloud.header.network.model.IpAddressSetType;
import com.gcloud.header.network.model.NetworkInterfaceType;
import com.gcloud.header.network.model.NetworkInterfaces;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@Transactional
public class VmBaseServiceImpl implements IVmBaseService {
    @Autowired
    private InstanceDao instanceDao;

    @Autowired
    private InstanceTypeDao instanceTypeDao;
    
    @Autowired
    private ZoneDao zoneDao;
    
    @Autowired
    private ZoneInstanceTypeDao zoneInstanceTypeDao;

    @Autowired
    private MessageBus bus;
    
    @Autowired
    private PortDao portDao;
    
    @Autowired
    private FloatingIpDao floatingIpDao;
    
    @Autowired
    private ImageDao imageDao;
    
    @Override
    public void startInstance(String instanceId) {
        startInstance(instanceId, true, true);
    }

    @Override
    public void startInstance(String instanceId, boolean inTask, boolean handleResource) {

        VmInstance vm = instanceDao.getById(instanceId);
        if (vm == null) {
            throw new GCloudException("0010202::找不到云服务器");
        }

        if (!instanceDao.updateInstanceStepState(instanceId, VmStepState.STARTING, inTask, VmState.STOPPED)) {
            throw new GCloudException("0010204::云服务器当前状态不能开机");
        }

        if(handleResource){
            Dispatcher.dispatcher().assignNode(vm.getHostname(), vm.getCore(), vm.getMemory());
        }

        StartInstanceMsg startInstanceMsg = new StartInstanceMsg();
        startInstanceMsg.setInstanceId(instanceId);
        startInstanceMsg.setServiceId(MessageUtil.computeServiceId(vm.getHostname()));
        startInstanceMsg.setHandleResource(handleResource);
        bus.send(startInstanceMsg);

    }

    @Override
    public void stopInstance(String instanceId) throws GCloudException {
        stopInstance(instanceId, true, true);
    }

    @Override
    public void stopInstance(String instanceId, boolean inTask, boolean handleResource) throws GCloudException {
        VmInstance vm = instanceDao.getById(instanceId);
        if (vm == null) {
            throw new GCloudException("0010302::找不到云服务器");
        }

        if (!instanceDao.updateInstanceStepState(instanceId, VmStepState.STOPPING, inTask, VmState.RUNNING)){
            throw new GCloudException("0010304::云服务器当前状态不能关机");
        }

        StopInstanceMsg stopInstanceMsg = new StopInstanceMsg();
        stopInstanceMsg.setInstanceId(vm.getId());
        stopInstanceMsg.setServiceId(MessageUtil.computeServiceId(vm.getHostname()));
        stopInstanceMsg.setHandleResource(handleResource);

        bus.send(stopInstanceMsg);

    }

    @Override
    public void rebootInstance(String instanceId, Boolean forceStop) throws GCloudException {
        rebootInstance(instanceId, true);
    }

    @Override
    public void rebootInstance(String instanceId, Boolean forceStop, boolean inTask) throws GCloudException {
        VmInstance vm = instanceDao.getById(instanceId);
        if (vm == null) {
            throw new GCloudException("0010402::找不到云服务器");
        }
        if (!instanceDao.updateInstanceStepState(instanceId, VmStepState.REBOOTING, inTask, VmState.RUNNING)){
            throw new GCloudException("0010404::云服务器当前状态不能重启");
        }

        RebootInstanceMsg rebootInstanceMsg = new RebootInstanceMsg();
        rebootInstanceMsg.setInstanceId(vm.getId());
        rebootInstanceMsg.setServiceId(MessageUtil.computeServiceId(vm.getHostname()));
        rebootInstanceMsg.setForceStop(forceStop);
        bus.send(rebootInstanceMsg);

    }

    @Override
    public PageResult<InstanceTypeItemType> describeInstanceTypes(DescribeInstanceTypesParams params) {

        if (params == null) {
            params = new DescribeInstanceTypesParams();
        }

        return instanceTypeDao.describeInstanceTypes(params, InstanceTypeItemType.class);

    }

	@Override
	public void modifyInstanceAttribute(String instanceId, String instanceName, String password, String taskId) {
		VmInstance vm = instanceDao.getById(instanceId);
        if (vm == null) {
            throw new GCloudException("0010503::找不到云服务器");
        }
        if(StringUtils.isNotBlank(instanceName)) {
        	List<String> updateFields = new ArrayList<String>();
        	updateFields.add(vm.updateAlias(instanceName));
        	instanceDao.update(vm, updateFields);
        	CacheContainer.getInstance().put(CacheType.INSTANCE_ALIAS, instanceId, instanceName);//修改缓存
        }
        
        if(StringUtils.isNotBlank(password)) {
        	ModifyPasswordMsg modifyMsg = new ModifyPasswordMsg();
        	modifyMsg.setInstanceId(vm.getId());
        	modifyMsg.setServiceId(MessageUtil.computeServiceId(vm.getHostname()));
        	modifyMsg.setPassword(password);
        	if(StringUtils.isNotBlank(taskId)) {
        		modifyMsg.setTaskId(taskId);
        	}
            bus.send(modifyMsg);
        }
        
	}

	@Override
	public PageResult<InstanceAttributesType> describeInstances(DescribeInstancesParams params, CurrentUser currentUser) {
		PageResult<InstanceAttributesType> pages = instanceDao.describeInstances(params, currentUser, InstanceAttributesType.class);
		List<AvailableZoneEntity> zones = zoneDao.findAll();
		Map<String, String> zoneMap = zones.stream().collect(Collectors.toMap(AvailableZoneEntity::getId, AvailableZoneEntity::getName));
		//加上浮动IP列表、网卡列表
		List<InstanceAttributesType> lists = pages.getList();
		for(InstanceAttributesType item:lists) {
			List<FloatingIp> ips = floatingIpDao.findByProperty("instanceId", item.getInstanceId());
            IpAddressSetType ipAddressSetType = new IpAddressSetType();
			List<String> ipAddrs = new ArrayList<>();
			for(FloatingIp ip : ips) {
                ipAddrs.add(ip.getFloatingIpAddress());
			}
            ipAddressSetType.setIpAddress(ipAddrs);
			item.setEipAddress(ipAddressSetType);

            NetworkInterfaces networkInterfaces = new NetworkInterfaces();
            networkInterfaces.setNetworkInterface(portDao.getInstanceNetworkInterfaces(item.getInstanceId(), NetworkInterfaceType.class));
			item.setNetworkInterfaces(networkInterfaces);
            if (StringUtils.isNotBlank(item.getTaskState())) {
                item.setStatus(item.getTaskState());
            }else if(StringUtils.isNotBlank(item.getStepState())){
                item.setStatus(item.getStepState());
            }
            
            //中文状态的转换
            item.setCnStatus(VmState.getCnName(item.getStatus()));
            item.setZoneName(zoneMap.get(item.getZoneId()));
            
            //填充虚拟机列表的私有网络IP
            IpAddressSetType innerIpAddress = new IpAddressSetType();
            List<String> ipList = new ArrayList<>();
            for (NetworkInterfaceType networkInterface : networkInterfaces.getNetworkInterface()) {
            	ipList.add(networkInterface.getPrimaryIpAddress());
			}
            innerIpAddress.setIpAddress(ipList);
            item.setInnerIpAddress(innerIpAddress);
		}
		return pages;
	}

    @Override
    public void cleanState(String instanceId, Boolean inTask) {
        if(inTask != null && inTask){
            instanceDao.cleanStepState(instanceId);
        }else{
            instanceDao.cleanState(instanceId);
        }
    }

    @Override
    public String queryInstanceVNC(String instanceId) {
        VmInstance vm = instanceDao.getById(instanceId);
        if (vm == null) {
            throw new GCloudException("0010202::找不到云服务器");
        }

        if (! vm.getState().equals(VmState.RUNNING.value())) {
            throw new GCloudException("0010801::非运行状态无法连接VNC");
        }

        QueryInstanceVNCMsg msg = new QueryInstanceVNCMsg();
        msg.setInstanceId(instanceId);
        msg.setServiceId(MessageUtil.computeServiceId(vm.getHostname()));
        QueryInstanceVNCMsgReply reply = bus.call(msg, QueryInstanceVNCMsgReply.class);

        NoVncUtil.addToken(msg.getInstanceId(), reply.getHostIp(), Integer.valueOf(reply.getPort()));
        return NoVncUtil.generateVncUrl(msg.getInstanceId());
    }

	@Override
	public void createInstanceType(CreateInstanceTypeParams params, CurrentUser currentUser) {
		List<InstanceType> instanceType = instanceTypeDao.findByProperty(InstanceType.NAME, params.getName());
		if(instanceType != null && !instanceType.isEmpty()) {
			log.error("0011402::已有该实例类型");
			throw new GCloudException("0011402::已有该实例类型");
		}
		
		InstanceType item = new InstanceType();
		String uuid = UUID.randomUUID().toString();
		if(StringUtils.isBlank(uuid)) {
		}
		
		//数据赋值
		item.setId(uuid);
		item.setName(params.getName());
		item.setVcpus(params.getCpu());
		item.setMemoryMb(params.getMemory());
		item.setDeleted(false);
		item.setCreatedTime(new Date());
		//enabled字段
		item.setEnabled(params.isEnabled());
		
		try {
			instanceTypeDao.save(item);
		} catch(Exception e) {
			log.error("创建实例类型失败，原因：【"+ e.getCause() + "::" + e.getMessage() +"】");
			throw new GCloudException("0011403::创建实例类型失败");
		}
		
	}

	@Override
	public void deleteInstanceType(DeleteInstanceTypeParams params, CurrentUser currentUser) {
		InstanceType instanceType = instanceTypeDao.getById(params.getId());
		if(instanceType == null) {
			log.error("0011502::不存在该实例类型");
			throw new GCloudException("0011502::不存在该实例类型");
		}
		//TODO 如果有虚拟机在使用
		Map<String, Object> instanceParams = new HashMap<>();
		instanceParams.put(VmInstance.INSTANCE_TYPE, params.getId());
		List<VmInstance> instanceList = instanceDao.findByProperties(instanceParams);
		if(instanceList != null && !instanceList.isEmpty()) {
			log.error("0011503::无法删除该实例类型，已有实例使用该实例类型");
			throw new GCloudException("0011503::无法删除该实例类型，已有实例使用该实例类型");
		}
		
		try {
			instanceTypeDao.deleteById(params.getId());
		} catch(Exception e) {
			log.error("删除实例类型失败，原因：【"+ e.getCause() + "::" + e.getMessage() +"】");
			throw new GCloudException("0011504::删除实例类型失败");
		}
	}

	@Override
	public void modifyInstanceType(ModifyInstanceTypeParams params, CurrentUser currentUser) {
		InstanceType instanceType = instanceTypeDao.getById(params.getId());
		if(instanceType == null) {
			log.error("0011604::不存在该实例类型");
			throw new GCloudException("0011604::不存在该实例类型");
		}
		
		//TODO (有没有必要。。。)不可用状态下无法进行修改
//		if(!instanceType.isEnabled()) {
//			log.error("0011607::该实例类型处于不可用状态，无法进行修改");
//			throw new GCloudException("0011607::该实例类型处于不可用状态，无法进行修改");
//		}
		
		Map<String, Object> instanceParams = new HashMap<>();
		instanceParams.put(VmInstance.INSTANCE_TYPE, params.getId());
		List<VmInstance> instanceList = instanceDao.findByProperties(instanceParams);
		if(instanceList != null && !instanceList.isEmpty()) {
			log.error("0011605::无法修改该实例类型，已有实例在使用该实例类型");
			throw new GCloudException("0011605::无法修改该实例类型，已有实例在使用该实例类型");
		}
		
		instanceType.setMemoryMb(params.getMemory());
		instanceType.setVcpus(params.getCpu());
		
		List<String> fields = new ArrayList<>();
		fields.add(InstanceType.MEMORY_MB);
		fields.add(InstanceType.VCPUS);
		
		try{
			instanceTypeDao.update(instanceType, fields);
		} catch(Exception e) {
			log.error("修改实例类型失败，原因：【"+ e.getCause() + "::" + e.getMessage() +"】");
			throw new GCloudException("0011606::修改实例类型失败");
		}
	}

	@Override
	public DetailInstanceType detailInstanceType(DetailInstanceTypeParams params, CurrentUser currentUser) {
		DetailInstanceType response = instanceTypeDao.getById(params.getId(), DetailInstanceType.class);
		if(response == null) {
			log.error("0011702::不存在该实例类型");
			throw new GCloudException("0011702::不存在该实例类型");
		}
		
		
		List<ZoneInfo> zones = instanceTypeDao.getZonesByInstanceType(params.getId(), ZoneInfo.class);
		response.setAvailableZones(zones);
		
		response.setMemoryMb(Math.ceil(response.getMemoryMb() == null ? 0 : response.getMemoryMb()/ 1024));
		response.setVcpus(response.getVcpus() == null ? 0 : response.getVcpus());
		
		return response;
	}

	@Override
	public void associateInstanceType(AssociateInstanceTypeParams params, CurrentUser currentUser) {
		InstanceType instanceType = instanceTypeDao.getById(params.getInstanceTypeId());
		if(instanceType == null) {
			log.error("0011803::不存在该实例类型");
			throw new GCloudException("0011803::不存在该实例类型");
		}
		
		//添加enabled字段处理
		if(!instanceType.isEnabled()) {
			log.error("0011806::该实例类型不可用");
			throw new GCloudException("0011806::该实例类型不可用");
		}
		
		//判断参数中的可用区是否有不存在的。逻辑：根据参数查询是否有相关数据，然后参数去掉查询到的，剩下的就是不存在的了
		List<String> notExist = new ArrayList<>();
		notExist.addAll(params.getZoneIds());
		List<AvailableZoneEntity> zoneList = zoneDao.findByIds(params.getZoneIds());
		List<String> zoneIdsList = new ArrayList<>();
		for (AvailableZoneEntity zone : zoneList) {
			zoneIdsList.add(zone.getId());
		}
		notExist.removeAll(zoneIdsList);
		if(!notExist.isEmpty()) {
			log.error("实例类型和可用区关联失败，原因：【可用区"+ notExist.toString() +"不存在】");
			throw new GCloudException("0011804::不存在可用区 "+ notExist.toString());
		}
		
		//判断参数中的需要删除的。逻辑：查询出所有已经绑定的可用区id，去掉参数的可用区id，剩下的就是需要删除的
		Map<String, Object> zitParams = new HashMap<>();
		zitParams.put(ZoneInstanceTypeEntity.INSTANCE_TYPE_ID, params.getInstanceTypeId());
		List<ZoneInstanceTypeEntity> zitList = zoneInstanceTypeDao.findByProperties(zitParams);
		
		List<String> zitIdsList = new ArrayList<>();
		for (ZoneInstanceTypeEntity zit : zitList) {
			zitIdsList.add(zit.getZoneId());
		}
		List<String> needDelete = new ArrayList<>();
		needDelete.addAll(zitIdsList);
		needDelete.removeAll(params.getZoneIds());
		
		//判断参数中需要添加的。逻辑：参数查询出来存在的可用区，去掉已经绑定的，剩下的就是需要绑定的
		List<String> needSave = new ArrayList<>();
		needSave.addAll(zoneIdsList);
		needSave.removeAll(zitIdsList);
		
		//判断可用区的可用性
		List<String> disableZone = new ArrayList<>();
		for (String zoneId : needSave) {
			for (AvailableZoneEntity zone : zoneList) {
				if(zoneId.equals(zone.getId())) {
					if(!zone.isEnabled()) {
						disableZone.add(zoneId);
					}
					break;
				}
			}
		}
		if(disableZone != null && !disableZone.isEmpty()) {
			log.error("实例类型和可用区关联失败，原因：【可用区 "+ disableZone.toString() +"不可用】");
			throw new GCloudException("0011805::可用区 "+ disableZone.toString() +"不可用");
		}
		
		//保存
		List<ZoneInstanceTypeEntity> saveZitEntitiy = new ArrayList<>();
		if(needSave != null && !needSave.isEmpty()) {
			for (String zoneId : needSave) {
				ZoneInstanceTypeEntity entity = new ZoneInstanceTypeEntity();
				entity.setInstanceTypeId(params.getInstanceTypeId());
				entity.setZoneId(zoneId);
				saveZitEntitiy.add(entity);
			}
		}

		try{
			zoneInstanceTypeDao.saveBatch(saveZitEntitiy);
			if(!needDelete.isEmpty()) {
				zoneInstanceTypeDao.deleteByInstanceTypeIdAndZoneId(params.getInstanceTypeId(), needDelete);
			}
		} catch(Exception e) {
			log.error("实例类型和可用区关联失败，原因：【"+ e.getCause() + "::" + e.getMessage() +"】");
			throw new GCloudException("0011806::实例类型和可用区关联失败");
		}
		
	}
	
	@Override
	public VmInstance getInstanceById(String instanceId) {
		return instanceDao.getById(instanceId);
	}

	@Override
	public DetailInstance detailInstance(DetailInstanceParams params, CurrentUser currentUser) {
		DetailInstance response = new DetailInstance();
		VmInstance vm = instanceDao.getById(params.getInstanceId());
		if(null == vm) {
			return response;
		}
		
		//TODO 这个ID可能有点问题
		response.setId(vm.getId());
		response.setCpu(vm.getCore());
		response.setCnStatus(VmState.getCnName(vm.getState()));
		response.setCreateTime(vm.getLaunchTime());
		
		String imageId = vm.getImageId();
		if(StringUtils.isNotBlank(imageId)) {
			Image image = imageDao.getById(imageId);
			response.setImageName(image == null ? null : image.getName());
		} else {
			response.setImageName(null);
		}
		response.setImageId(imageId);
		
		String instanceTypeId = vm.getInstanceType();
		if(StringUtils.isNotBlank(instanceTypeId)) {
			InstanceType instanceType = instanceTypeDao.getById(instanceTypeId);
			response.setInstanceTypeName(instanceType == null ? null : instanceType.getName());
		}
		response.setInstanceTypeId(instanceTypeId);
		
		response.setInstanceUuid(vm.getId());
		//计费类型？ G8没有
		response.setInternetChargeType(null);
		response.setInternetChargeTypeName(null);
		
		response.setInternetMaxBandwidthOut("");
		//TODO 这个需要确定
//		response.setIsTask(false);
		response.setMemory(vm.getMemory());
		response.setName(vm.getAlias());
		response.setStatus(vm.getState());
		//TODO 数据来源?
		response.setSystemCategoryId("");
		response.setSystemCategoryName("");
		response.setSystemDisk(vm.getDisk());
		
		String zoneId = vm.getZoneId();
		if(StringUtils.isNotBlank(zoneId)) {
			AvailableZoneEntity zone = zoneDao.getById(zoneId);
			response.setZoneName(zone == null ? null : zone.getName());
		} else {
			response.setZoneName(null);
		}
		response.setZoneId(zoneId);
		
		return response;
	}

	@Override
	public TplInstanceResponse tplInstances(ApiTplInstancesMsg msg) {
		TplInstanceResponse res = new TplInstanceResponse();
		List<TplInstanceItem> tplInstances = new ArrayList<TplInstanceItem>();
		DescribeInstancesParams params = new DescribeInstancesParams();
		params.setPageSize(9999);
		PageResult<InstanceAttributesType> pages = instanceDao.describeInstances(params, msg.getCurrentUser(), InstanceAttributesType.class);
		List<InstanceNetworkInterfaceItem> insInterfaces = portDao.getAllInstanceNetworkInfaceItem(msg.getCurrentUser(), InstanceNetworkInterfaceItem.class);
		Map<String, String> InstanceNetworkInterfaceMap = insInterfaces.stream().collect(Collectors.toMap(InstanceNetworkInterfaceItem::getInstanceId, InstanceNetworkInterfaceItem::getNetworkInterfaceItem,(key1 , key2)-> key2 ));
		for(InstanceAttributesType item:pages.getList()) {
			TplInstanceItem tplItem = new TplInstanceItem();
			tplItem.setAlias(item.getInstanceName());
			tplItem.setInstanceId(item.getInstanceId());
			
			TplNetworkInterfaceItems interfaces = new TplNetworkInterfaceItems();
			List<TplNetworkInterfaceItem> networkInterfaceItem = new ArrayList<TplNetworkInterfaceItem>();
			if(InstanceNetworkInterfaceMap.containsKey(item.getInstanceId())) {
				String networkInterfacesStr = InstanceNetworkInterfaceMap.get(item.getInstanceId());
				String[] networkInterfaces = networkInterfacesStr.split(",");
				for(String interfaceItem:networkInterfaces) {
					String[] interfaceInfos = interfaceItem.split("#");
					TplNetworkInterfaceItem tplInterface = new TplNetworkInterfaceItem();
					tplInterface.setNetworkInterfaceId(interfaceInfos[0]);
					tplInterface.setPrivateIp(interfaceInfos[1]);
					tplInterface.setvSwitchId(interfaceInfos[2]);
					
					networkInterfaceItem.add(tplInterface);
				}
				interfaces.setNetworkInterfaceItem(networkInterfaceItem);
				tplItem.setNetworkInterfaceItems(interfaces);
			}
			tplInstances.add(tplItem);
		}
		res.setInstance(tplInstances);
		return res;
	}
}
